package com.nervenets.general.advice;

import com.nervenets.general.Global;
import com.nervenets.general.config.ApplicationProperties;
import com.nervenets.general.redis.RedisMultiPointLocker;
import com.nervenets.general.utils.AESUtils;
import com.nervenets.general.utils.HttpTools;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.Vector;

/**
 * 封装返回结果，AES加密
 */
@Order(1)
@Configuration
@ControllerAdvice(basePackages = "com.nervenets")
@Slf4j
public class NerveNetsResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Resource
    private ApplicationProperties applicationProperties;
    @Resource
    private MappingJackson2HttpMessageConverter longToStringConverter;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object keys = HttpTools.getHttpRequestAttribute(Global.Constants.SESSION_LOCK_KEYS);
        if (null != keys) ((Vector<String>) keys).forEach(RedisMultiPointLocker::unlock);

        if (applicationProperties.isResponseEncrypt() && "application/json".equalsIgnoreCase(selectedContentType.toString())) {

            MappingJacksonValue jacksonValue = getOrCreateContainer(body);
            String value = longToStringConverter.getObjectMapper().writeValueAsString(jacksonValue.getValue());

            return AESUtils.encryptString(value);
        }
        return body;
    }

    protected MappingJacksonValue getOrCreateContainer(Object body) {
        return (body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new MappingJacksonValue(body));
    }
}
